package com.spdg.ring.adapter;

import java.util.ArrayList;
import java.util.List;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebSettings.LayoutAlgorithm;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.BaseAdapter;
import cn.wolf.http.HttpCallBack;
import cn.wolf.tools.AppHelper;

import com.spdg.ring.R;
import com.spdg.ring.RingBaseActivity;
import com.spdg.ring.bo.ArticleBo;
import com.spdg.ring.resp.ArticleResp;
import com.spdg.ring.sqlite.model.Article;
import com.spdg.ring.sqlite.model.ArticleList;

@SuppressLint({ "SetJavaScriptEnabled", "NewApi" })
public class GalleryAdapter extends BaseAdapter {
	private LayoutInflater mInflater;
	private RingBaseActivity mActivity;
	private List<ArticleList> list = new ArrayList<ArticleList>(1);
//	private Map<Integer, WebView> mWebViewMap = new HashMap<Integer, WebView>(1);

	private String pageTemplate = "file:///android_asset/show_article.html"; // 详细页面载入的HTML
	private int screenHeigt;

//	private int lastPos = -1;
	private WebView mTempWebView;

	public GalleryAdapter(RingBaseActivity mActivity, List<ArticleList> list) {
		this.mActivity = mActivity;
		if (list != null) {
			this.list = list;
		}
		mInflater = (LayoutInflater) mActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		screenHeigt = AppHelper.getScreenHeight(mActivity);
	}

	@Override
	public int getCount() {
		return list.size();
	}

	@Override
	public Object getItem(int position) {
		return list.get(position);
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		if (convertView == null) {
			convertView = mInflater.inflate(R.layout.gallery_article_item, null);
			initComponents(convertView, position);
		}

		// if (lastPos != position) {
		initData(convertView, position);
//		lastPos = position;
		// }

		return convertView;
	}

	protected void initData(View convertView, int pos) {
		ArticleList articleList = list.get(pos);

		// 初始化浏览器
		initBrowser(articleList, convertView, pos);

	}

	/**
	 * 初始化浏览器，获取相关数据
	 */
	private void initBrowser(ArticleList articleList, View convertView, int pos) {

		// 请求详细内容数据
		ArticleBo articleBo = new ArticleBo(mActivity, new GetDetailContentCallback(),
				articleList.getFile());
		articleBo.setParams(articleList.getSrc());
		articleBo.request(convertView);
	}

	private void initComponents(View convertView, int pos) {
		WebView mBrowser = (WebView) convertView.findViewById(R.id.article_browser);
		mBrowser.getSettings().setJavaScriptEnabled(true);
		mBrowser.getSettings().setLoadsImagesAutomatically(true);
		mBrowser.getSettings().setPluginsEnabled(true);
		// mBrowser.setBackgroundColor(Color.rgb(0xee, 0xee, 0xee));
//		mBrowser.getSettings().setLayoutAlgorithm(LayoutAlgorithm.SINGLE_COLUMN);
		mBrowser.getSettings().setBuiltInZoomControls(false); // 取消双击放大
		mBrowser.getSettings().setUseWideViewPort(false);
		mBrowser.getSettings().setAppCacheEnabled(true);
		mBrowser.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
		mBrowser.setWebViewClient(new GalleryWebviewClient());

//		mWebViewMap.put(pos, mBrowser);
		// mBrowser.setVerticalScrollBarEnabled(true);
		// mBrowser.setScrollbarFadingEnabled(true);
	}

	public boolean onKeyDown() {
//		WebView browser = mWebViewMap.get(lastPos);
		if (mTempWebView != null && mTempWebView.canGoBack()) {
			mTempWebView.goBack();
			return true;
		}
		return false;
	}

	class GalleryWebviewClient extends WebViewClient {
		@Override
		public boolean shouldOverrideUrlLoading(WebView view, String url) {
			mTempWebView = view;
			
			if (url.startsWith("newtab:")) {
				int start = url.indexOf("http");
				String tempUrl = url.substring(start);
				Uri uri = Uri.parse(tempUrl); //
				Intent intent = new Intent(Intent.ACTION_VIEW, uri);
				mActivity.startActivity(intent);
			} else {
				view.loadUrl(url);
				
			}
			return true;
//			return super.shouldOverrideUrlLoading(view, url);
		}
	}

	public class ShowNews {

		private Article mArticle;

		public ShowNews(Article article) {
			this.mArticle = article;
		}

		public String getTitle() {
			if (mArticle != null) {
				return mArticle.getTitle();
			}
			return "";
		}

		public String getTime() {
			if (mArticle != null) {
				return mArticle.getDate();
			}
			return "";
		}

		public String getBody() {
			if (mArticle != null) {
				return mArticle.getContent();
			}
			return "";
		}

		public int getScreenHeight() {
			return screenHeigt;
		}

		public boolean getIsSumSang() {
			String brand = AppHelper.getBrand();
			String model = AppHelper.getModel();
			// System.out.println("brand:" + brand);
			// System.out.println("model:" + model);
			if (brand == null || model == null) {
				return false;
			}

			if ("SAMSUNG".equals(brand.toUpperCase())) {
				return true;
			}
			return false;
		}
	}

	class GetDetailContentCallback implements HttpCallBack<ArticleResp> {

		@Override
		public void call(ArticleResp response) {
			if (response.isSuccess()) {
				Article article = response.getArticle();
				View convertView = response.getConvertView();
				WebView browser = (WebView) convertView.findViewById(R.id.article_browser);
				browser.addJavascriptInterface(new ShowNews(article), "news");
				// 加载页面
				browser.loadUrl(pageTemplate);

				// notifyDataSetChanged();
			}

		}

		@Override
		public void progress(Object... obj) {
		}

		@Override
		public void onNetWorkError() {

		}

	}

}
